<template>
  <div class="product-card" @click="goToDetail">
    <div class="product-image">
      <img
        v-if="product.mainImage"
        :src="getImageUrl(product.mainImage)"
        :alt="product.productName"
        @error="handleImageError"
      />
      <span v-else class="image-placeholder">商品图片</span>
    </div>
    <div class="product-info">
      <div class="product-name" :title="product.productName">{{ product.productName || '商品名称' }}</div>
      <div class="product-desc" :title="product.description">{{ product.description || '暂无描述' }}</div>
      <div class="product-price">¥ {{ formatPrice(product.price) }}</div>
      <div class="product-actions">
        <el-button
          type="primary"
          size="small"
          @click.stop="addToCart"
          :loading="addingToCart"
        >
          加入购物车
        </el-button>
        <el-button
          v-if="showFavorite"
          size="small"
          @click.stop="toggleFavoriteLocal"
          :class="{ 'is-favorite': isFavorite }"
          :loading="favoriteLoading"
          :icon="isFavorite ? 'StarFilled' : 'Star'"
        >
          {{ isFavorite ? '已收藏' : '收藏' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { toggleFavorite, checkFavorite } from '@/api/favorite'
import { addToCart as addToCartAPI } from '@/api/cart'
import { getImageUrl, handleImageError as handleImgError } from '@/utils/image'

const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  // 是否显示收藏按钮（某些场景可能不需要）
  showFavorite: {
    type: Boolean,
    default: true
  },
  // 初始收藏状态（用于避免重复请求）
  initialFavorite: {
    type: Boolean,
    default: null
  },
  // 是否在收藏列表页（收藏列表页点击收藏按钮应该移除）
  inFavoriteList: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['remove', 'favorite-changed'])

const router = useRouter()
const addingToCart = ref(false)
const isFavorite = ref(props.initialFavorite ?? false)
const favoriteLoading = ref(false)

const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

const goToDetail = () => {
  if (!props.product?.id) {
    console.warn('商品ID不存在')
    return
  }
  router.push('/product/' + props.product.id)
}

const addToCart = async () => {
  if (!props.product?.id) {
    ElMessage.warning('商品信息不完整')
    return
  }
  
  addingToCart.value = true
  try {
    const res = await addToCartAPI(props.product.id, 1)
    if (res.code === 200) {
      ElMessage.success('已添加到购物车')
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('添加失败，请稍后重试')
  } finally {
    addingToCart.value = false
  }
}

const toggleFavoriteLocal = async () => {
  if (!props.product?.id) {
    ElMessage.warning('商品信息不完整')
    return
  }
  
  favoriteLoading.value = true
  try {
    const res = await toggleFavorite(props.product.id)
    if (res.code === 200) {
      const newState = res.data
      isFavorite.value = newState
      
      // 如果在收藏列表页且取消收藏，触发移除事件
      if (props.inFavoriteList && !newState) {
        emit('remove', props.product.id)
      }
      
      // 触发收藏状态变化事件
      emit('favorite-changed', newState)
      
      ElMessage.success(newState ? '已添加到收藏' : '已取消收藏')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    favoriteLoading.value = false
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  if (!props.product?.id) return
  // 如果已经提供了初始状态，就不需要再请求
  if (props.initialFavorite !== null) {
    isFavorite.value = props.initialFavorite
    return
  }
  
  try {
    const res = await checkFavorite(props.product.id)
    if (res.code === 200) {
      isFavorite.value = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    // 失败时默认设为false，不影响用户体验
    isFavorite.value = false
  }
}

// 监听product变化，重新检查收藏状态
watch(() => props.product?.id, (newId) => {
  if (newId) {
    checkFavoriteStatus()
  }
}, { immediate: false })

// 监听初始收藏状态变化
watch(() => props.initialFavorite, (newVal) => {
  if (newVal !== null) {
    isFavorite.value = newVal
  }
})

onMounted(() => {
  checkFavoriteStatus()
})

// 使用统一的图片错误处理
const handleImageError = handleImgError
</script>

<style lang="scss" scoped>
.product-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  }

  .product-image {
    height: 180px;
    background-color: #f5f7fa;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .image-placeholder {
      color: #909399;
      font-size: 14px;
    }
  }

  .product-info {
    padding: 15px;
  }

  .product-name {
    font-weight: 500;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .product-desc {
    color: #909399;
    font-size: 13px;
    margin-bottom: 10px;
    height: 36px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .product-price {
    color: #f56c6c;
    font-weight: 600;
    font-size: 18px;
    margin-bottom: 12px;
  }

  .product-actions {
    display: flex;
    justify-content: space-between;
    gap: 8px;

    .el-button {
      flex: 1;
    }

    .is-favorite {
      color: #f56c6c;
      border-color: #f56c6c;
      background-color: #fef0f0;
      
      &:hover {
        background-color: #fee;
        border-color: #f56c6c;
      }
    }
  }
}
</style>

